package cn.antcore.resources.util;

import java.util.*;

public class AntUtil {

    /**
     * 标准化结果
     * <p>
     *     处理resourceMap中未处理的数组型配置文件为 Object[]
     *
     * @param resourceMap resources.getResources()的结果
     * @return 标准化的结果
     *
     * @author warren
     */
    public static Map<String,Object> standardization(Map<Object,Object> resourceMap){
        Set<Object> keySet = resourceMap.keySet();
        Map<String, Object> configMap = new HashMap<>();
        for (Object o : keySet) {
            String key = (String) o;
            if (key.contains("[")) {
                String[] split = key.split("\\[");
                String K = split[0];
                String b = split[1].replace("]", "");
                int I = Integer.parseInt(b);

                if (!configMap.containsKey(K)) {
                    configMap.put(K, new ArrayList<>());
                }
                Object o1 = configMap.get(K);
                if (o1 instanceof List) {
                    ConfigObject configObject = new ConfigObject();
                    configObject.index = I;
                    configObject.v = resourceMap.get(key);
                    ((List) o1).add(configObject);
                }
            } else {
                if (configMap.containsKey(key)) {
                    throw new RuntimeException("重复定义 property , property key "+key);
                }else{
                    configMap.put(key,resourceMap.get(key));
                }
            }
        }

        Set<String> ks = configMap.keySet();
        Map<String,Object> cm = new HashMap<>();
        for (String k : ks) {
            Object o = configMap.get(k);
            if(o instanceof List){
                if(((List) o).size() > 0 && ((List) o).get(0) instanceof  ConfigObject) {
                    List<ConfigObject> list = (List) o;
                    Collections.sort(list);
                    Object[] vs = new Object[list.size()];
                    for (int i = 0; i < list.size(); i++) {
                        vs[i] = list.get(i).v;
                    }
                    cm.put(k, vs);
                }else{
                    cm.put(k,((List) o).toArray());
                }
            }else{
                cm.put(k,configMap.get(k));
            }
        }
        return cm;
    }

    /**
     * 用于描述配置数组的内部类
     */
    private static class ConfigObject implements Comparable<ConfigObject>{
        public int index;

        public Object v;

        @Override
        public int compareTo(ConfigObject o) {
            return Integer.compare(this.index,o.index);
        }
    }

}
